package com.sxdz.web.send

import com.sxdz.constant.CommonConstant
import com.sxdz.constant.MessageConstant
import com.sxdz.controller.service.send.ISendInfoService
import com.sxdz.controller.service.send.SendInfoService
import com.sxdz.controller.service.wechat.IWechatSubService
import com.sxdz.models.TProgramInfo
import com.sxdz.models.TSendInfo
import com.sxdz.models.TblWechatSubscribe
import com.sxdz.models.common.JsonResult
import groovy.transform.CompileStatic
import groovy.transform.TypeChecked
import org.apache.poi.util.LongField
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.ResponseBody
import org.springframework.web.bind.annotation.RestController

import javax.servlet.http.HttpServletRequest
import java.util.logging.Logger

/**
 * Created by andy on 2016/8/4.
 */

@CompileStatic
@TypeChecked
@RestController
@RequestMapping("send")
class SendInfoAction {

    @Autowired
    private ISendInfoService sendInfoService;
    @Autowired
    private IWechatSubService wechatSubService;

    org.slf4j.Logger logger = LoggerFactory.getLogger(this.getClass())

    /***
     * 查询所有的寄送地址
     */
    @RequestMapping(value = "getList/{openid}", method = RequestMethod.GET)
    @ResponseBody
    getAllSend(@PathVariable("openid") String openid) {
        Map<String, Object> params = [:]
        TblWechatSubscribe wechatSubscribe = wechatSubService.findObj([openid: openid] as Map)
        if (wechatSubscribe == null) {
            return new JsonResult<Object>(MessageConstant.FAILURE.code, "未获取到微信用户信息", null)
        }
        Long userId = wechatSubscribe.getSubcribeId() as Long
        List<TSendInfo> tSendInfoList = new ArrayList<TSendInfo>();
        tSendInfoList=sendInfoService.findObj(userId)
        return new JsonResult<Object>(MessageConstant.SUCCESS.code.toString(), "", tSendInfoList)

    }
    /***
     * 添加寄送地址
     */
    @RequestMapping(value = "addSendInfo", method = RequestMethod.POST)
    @ResponseBody
    addSendInfo(TSendInfo sendInfo, HttpServletRequest request) {
        try {
            Map<String, Object> params = [:];
            //根据openId 获取userId
            String openid = request.getParameter("openid");
            TblWechatSubscribe wechatSubscribe = wechatSubService.findObj([openid: openid] as Map)
            if (wechatSubscribe == null) {
                return new JsonResult<Object>(MessageConstant.FAILURE.code, "未获取到微信用户信息", null)
            }
            Long userId = wechatSubscribe.getSubcribeId() as Long
            int count
            //判断同一个userId只可以添加三条
            params << [userId: userId];
            count = sendInfoService.selectCountSend(params);
            if (count >= 3) {
                return new JsonResult<Object>(MessageConstant.FAILURE.code.toString(),
                        "result", "新增失败,只能有三个地址")
            }
            //判断是否默认  位默认则更新其他地址为非默认
            if ("1".equals(sendInfo.isDefault)) {
                Map<String, Object> param = [:];
                param << [isDefaultNew: "0"]
                param << [isDefault: "1"]
                param << [userId: userId];
                try {
                    int i = sendInfoService.updateIsDefault(param);
                }
                catch (Exception e1) {
                    e1.printStackTrace();
                }
            }
            sendInfo.setUserId(userId);
            sendInfo.setIsActive(CommonConstant.IsActive.True.value)
            sendInfo.setCreateTime(new Date().getTime())
            Integer countss;
            try {
                countss = sendInfoService.addSendInfo(sendInfo) as Integer;
            }
            catch (Exception e) {
                e.printStackTrace();
            }
            if (countss == 1) {
                return new JsonResult<Object>(MessageConstant.SUCCESS.code.toString(), "result", "地址新增成功")
            } else {
                return new JsonResult<Object>(MessageConstant.FAILURE.code.toString(), "result", "新增失败")
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult<Object>(MessageConstant.SYS_ERROR.code.toString(), "result", "系统异常")
        }
    }
    /***
     * 删除制定的寄送地址
     */
    @RequestMapping(value = "delSend/{id}", method = RequestMethod.GET)
    @ResponseBody
    delSend(@PathVariable("id") Long id) {
        int del = sendInfoService.deleteSend(id);
        if (del > 0) {
            return new JsonResult<Object>(MessageConstant.SUCCESS.code.toString(), "result", "地址删除成功")
        } else {
            return new JsonResult<Object>(MessageConstant.FAILURE.code.toString(), "result", "删除失败")
        }

    }
    /***
     * 根据 id查询 寄送地址
     */
    @RequestMapping(value = "updataSendById/{id}", method = RequestMethod.GET)
    @ResponseBody
    updataSendById(@PathVariable("id") Long id) {

        TSendInfo sendInfo = sendInfoService.selectById(id);
        if (sendInfo != null) {
            return new JsonResult<Object>(MessageConstant.SUCCESS.code.toString(), "result",sendInfo )
        } else {
            return new JsonResult<Object>(MessageConstant.FAILURE.code.toString(), "result", "获取失败")
        }

    }
    /***
     * 修改寄送地址
     */
    @RequestMapping(value = "updataSend", method = RequestMethod.POST)
    @ResponseBody
    updataSend(TSendInfo sendInfo,HttpServletRequest request) {

       String openid = request.getParameter("openid");
        TblWechatSubscribe wechatSubscribe = wechatSubService.findObj([openid: openid] as Map)
        if (wechatSubscribe == null) {
            return new JsonResult<Object>(MessageConstant.FAILURE.code, "未获取到微信用户信息", null)
        }
        Long userId = wechatSubscribe.getSubcribeId() as Long
         if("1".equals(sendInfo.isDefault)) {
         Map<String, Object> param = [:];
         param << [isDefaultNew: "0"]
            param << [isDefault: "1"]
             param << [userId: userId]
          try {
                 int i = sendInfoService.updateIsDefault(param);
         }
          catch (Exception e1) {
              e1.printStackTrace();
         }}
    int updatecount;
    try {
        updatecount = sendInfoService.updateSend(sendInfo);
    } catch (Exception e) {
        e.printStackTrace()
    }
        if (updatecount > 0) {
            return new JsonResult<Object>(MessageConstant.SUCCESS.code.toString(), "result", "地址修改成功")
        } else {
            return new JsonResult<Object>(MessageConstant.FAILURE.code.toString(), "result", "修改失败")
        }

    }

}
